<?php

namespace App\Service;

use App\Model\HealthRecord;
use Hyperf\Logger\LoggerFactory;
use Psr\Log\LoggerInterface;

class HealthLogService
{
    protected LoggerInterface $logger;

    public function __construct(LoggerFactory $loggerFactory)
    {
        $this->logger = $loggerFactory->get('health_record');
    }

    public function createLog(array $record)
    {
        $this->logger->info('create_health_info', $record);
        if (empty($record['record_time'])) {
            $record['record_time'] = date('Y-m-d H:i:s');
        }
        // 通过 record_time 去重
        /** @var null|HealthRecord $exRecord */
        $exRecord = HealthRecord::query()->where('record_time', $record['record_time'])->first();
        if (! $exRecord) {
            HealthRecord::query()->create($record);
            return;
        }
        if ($record['blood_pressure_high']) {
            $exRecord->blood_pressure_high = $record['blood_pressure_high'];
        }
        if ($record['blood_pressure_low']) {
            $exRecord->blood_pressure_low = $record['blood_pressure_low'];
        }
        if ($record['blood_sugar']) {
            $exRecord->blood_sugar = $record['blood_sugar'];
        }
        if ($record['heart_rate']) {
            $exRecord->heart_rate = $record['heart_rate'];
        }
        $exRecord->save();
        $this->logger->info('update_record');
    }

    public function fetchRecords(array $search)
    {
        // 默认最近 7 天
        $last7days = date('Y-m-d H:i:s', strtotime('-7 days'));
        $startTime = $search['start_time'] ?? $last7days;
        $endTime = $search['end_time'] ?? date('Y-m-d H:i:s');
        $builder = HealthRecord::query();
        if (! empty($search['name'])) {
            $builder->where('name', $search['name']);
        }
        $records = $builder
            ->where('blood_pressure_high', '>', 0) // 血压心率在一起记录
            ->where('record_time','>=', $startTime)
            ->where('record_time', '<=', $endTime)->get();
        return $records->toArray();
    }

    public function fetchBloodSugar()
    {
        // 默认最近 7 天
        $last7days = date('Y-m-d H:i:s', strtotime('-7 days'));
        $startTime = $search['start_time'] ?? $last7days;
        $endTime = $search['end_time'] ?? date('Y-m-d H:i:s');
        $builder = HealthRecord::query();
        if (! empty($search['name'])) {
            $builder->where('name', $search['name']);
        }
        $records = $builder
            ->where('blood_sugar', '>', 0) // 血压心率在一起记录
            ->where('record_time','>=', $startTime)
            ->where('record_time', '<=', $endTime)->get();
        return $records->toArray();
    }

    public function remove(int $id)
    {
        HealthRecord::query()->where('id', $id)->delete();
    }
}